<?php
require_once 'config.php';
require_once 'AlibabaSDK.php';
require_once 'Database.php';

// 初始化SDK和数据库连接
$sdk = new AlibabaSDK(APP_KEY, APP_SECRET);
$db = new Database(DB_HOST, DB_USER, DB_PASS, DB_NAME);

// 设置access_token
$accessToken = '33b3796c-4274-4a41-8aab-92e83df98498';

// 处理分类数据
function processCategoryData($category) {
    $data = [];
    foreach($category['result']['children'] as $cate){
        // 使用 translatedName 作为分类名称
        $name = $cate['translatedName'] ?? '未知分类';
        
        $data[] = [
            'categoryID' => intval($cate['categoryId'] ?? 0),
            'chineseName' => $name,  // 使用翻译后的名称
            'parentCateId' => intval($cate['parentCateId'] ?? 0),
            'level' => intval($cate['level'] ?? 1),
            'create_time' => time()
        ];
        
        echo "处理分类: ID={$cate['categoryId']}, Name={$name}\n";
    }
    return $data;
}

// 爬取商品分类
function crawlCategories($sdk, $db, $accessToken) {
    try {
        $targetCategories = [
            'Мужская одежда' => '1',//男装
            'Женская одежда' => '2',//女装
            'Детская одежда' => '3',//童装
            'Игрушки' => '4',//玩具
            'Бытовая техника' => '5'//小家电
        ];
        
        // 处理一级分类
        $categoryData = [];
        foreach ($targetCategories as $name => $categoryId) {
            $categoryData[] = [
                'id' => intval($categoryId),
                'chineseName' => $name,
                'parentCateId' => 0,
                'level' => 1,
                'create_time' => time()
            ];
        }
        
        $result = $db->saveCategory($categoryData);
        if (!$result) {
            echo "保存分类失败！\n";
        } else {
            echo "保存分类成功！\n";
        }
        
        // 获取二级分类
        foreach($categoryData as $cate){
            $subcat = getSubCategories($sdk, $db, $cate['chineseName'], $accessToken,$cate['id']);
            $db->saveCategory($subcat);
        }
        
    } catch (Exception $e) {
        echo "获取分类出错：" . $e->getMessage() . "\n";
    }
}

// 获取子分类
function getSubCategories($sdk, $db, $cateName, $accessToken,$pid) {
    try {
        $params = [
            'language' => 'ru',  // 使用俄语
            'cateName' => $cateName
        ];
        
        $response = $sdk->execute(
            'com.alibaba.fenxiao.crossborder', 
            'category.translation.getByKeyword',
            $params,
            $accessToken
        );
        if (!isset($response['result']) || !isset($response['result']['result'])) {
            echo "获取子分类响应格式错误\n".$response['result']['message'];
            return [];
        }
        
        // 处理二级分类数据
        $subCategories = [];
        if (isset($response['result']['result'])) {
            foreach ($response['result']['result'] as $cate) {
                $name = $cate['translatedName'] ?? '未知分类';
                
                $subCategories[] = [
                    'chineseName' => $name,  // 使用翻译后的名称
                    'parentId' => intval($pid ?? 0),
                    'level' => intval($cate['level'] ?? 1),
                    'create_time' => time()
                ];
                
                echo "处理二级分类: ID={$cate['categoryId']}, Name={$name}\n";
            }
        }
        
        return $subCategories;
        
    } catch (Exception $e) {
        echo "获取子分类出错：" . $e->getMessage() . "\n";
        return [];
    }
}

// 开始爬取
try {
    echo "开始爬取分类...\n";
    crawlCategories($sdk, $db, $accessToken);
    echo "爬取完成！\n";
} catch (Exception $e) {
    echo "发生错误：" . $e->getMessage() . "\n";
} finally {
    $db->close();
} 